package cloud.tianai.mate.captcha.interceptor.impl;

import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.common.response.CodeDefinition;
import cloud.tianai.captcha.common.util.CaptchaTypeClassifier;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
import cloud.tianai.captcha.interceptor.Context;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cloud.tianai.mate.captcha.interceptor.group.FeaturesCaptchaInterceptorGroup;

/**
 * @Author: 天爱有情
 * @date 2024/7/12 10:25
 * @Description 滑动启始位置校验器
 */
public class SliderStartPosCaptchaInterceptor implements CaptchaInterceptor {
    public static final CodeDefinition DEFINITION = new CodeDefinition(60003, "pos check fail");
    public static final String KEY = "sliderStartPos";


    @Override
    public String getName() {
        return "slider_start_pos_check";
    }

    @Override
    public ApiResponse<?> afterValid(Context context, String type, ImageCaptchaTrack imageCaptchaTrack, AnyMap validData, ApiResponse<?> basicValid) {
        ApiResponse<?> preResult = CaptchaInterceptor.super.beforeValid(context, type, imageCaptchaTrack, validData);
        if (!preResult.isSuccess()) {
            return preResult;
        }
        if (!basicValid.isSuccess()) {
            return context.getGroup().afterValid(context, type, imageCaptchaTrack, validData, basicValid);
        }
        AnyMap featureMap = context.getData(FeaturesCaptchaInterceptorGroup.DATA_FEATURES, AnyMap.class);
        if (!CaptchaTypeClassifier.isSliderCaptcha(type) || featureMap == null) {
            return ApiResponse.ofSuccess();
        }

        ImageCaptchaTrack.Track firstTrack = imageCaptchaTrack.getTrackList().get(0);
        Integer startLeft = imageCaptchaTrack.getLeft();
        Integer startTop = imageCaptchaTrack.getTop();
        float x = firstTrack.getX() - startLeft;
        float y = firstTrack.getY() - startTop;
        // 计算启始点，正常用户不可能每次都一致，记录最近10次的
        String sourceHistoryPosStr = featureMap.getString(KEY, "");
        String historyPosStr = sourceHistoryPosStr;
        int index;
        int maxPos = 0;
        int count = 0;
        int quantityHits = 0;
        while ((index = historyPosStr.lastIndexOf(",")) != -1) {
            String substring = historyPosStr.substring(index + 1);
            historyPosStr = historyPosStr.substring(0, index);
            String[] split1 = substring.split(":");
            float hisX = Float.parseFloat(split1[0]);
            float hisY = Float.parseFloat(split1[1]);
            if (Math.abs(x - hisX) < 1 || Math.abs(y - hisY) < 1) {
                quantityHits++;
            }
            count++;
            // 最近三组
            if (maxPos == 0 && count >= 2) {
                maxPos = index;
            }
        }
        if ((quantityHits != 0 && count != 0) && (float) quantityHits / count > 0.2) {
            context.end();
            return ApiResponse.ofMessage(DEFINITION);
        }
        if (!sourceHistoryPosStr.isEmpty()) {
            sourceHistoryPosStr += ",";
        }
        if (maxPos > 0) {
            // 截取一截
            sourceHistoryPosStr = sourceHistoryPosStr.substring(maxPos + 1);
        }
        sourceHistoryPosStr += x + ":" + y;
        featureMap.put(KEY, sourceHistoryPosStr);
        return ApiResponse.ofSuccess();
    }
}
